/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package th.manager;

import com.google.inject.Inject;
import com.wideplay.warp.persist.Transactional;
import java.text.DecimalFormat;
import java.util.Arrays;
import org.hibernate.Query;
import org.hibernate.Session;
import th.dao.SeqNumDAO;
import th.model.SeqNum;

/**
 *
 * @author fikri
 */
public class SequenceManager {

    @Inject
    protected com.google.inject.Provider<Session> sessionProvider;
    @Inject
    private SeqNumDAO seqNumDAO;

    public String getSequence(String msgId) {
        Session session = sessionProvider.get();
        Query query = session.createQuery(
                "select a.num from SeqNum a "
                + "where a.urusan = :msgId");
        query.setParameter("msgId", msgId);

        int seq = (Integer)query.iterate().next() + 1;


        return intToString(seq, 4);
    }
    
    public String getSequenceWithoutLeadingZero(String msgId) {
        Session session = sessionProvider.get();
        Query query = session.createQuery(
                "select a.num from SeqNum a "
                + "where a.urusan = :msgId");
        query.setParameter("msgId", msgId);

        int seq = (Integer)query.iterate().next() + 1;
        return String.valueOf(seq);
    }

    @Transactional
    public void updateSequece(SeqNum seq) {
        int seqNo = seq.getNum();
        if (seqNo == 9999) {
            seq.setNum(0);
        }
        seqNumDAO.update(seq);
    }
    
    @Transactional
    public void updateCounter(SeqNum seq) {
        seqNumDAO.update(seq);
    }

    static String intToString(int num, int digits) {
        assert digits > 0 : "Invalid number of digits";

        // create variable length array of zeros
        char[] zeros = new char[digits];
        Arrays.fill(zeros, '0');
        // format number as String
        DecimalFormat df = new DecimalFormat(String.valueOf(zeros));

        return df.format(num);
    }
}
